package com.jc.service.role;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.CheckNullUtils;
import com.jc.common.util.WebUtils;
import com.jc.ds.mapper.RoleMapper;
import com.jc.ds.mapper.RolePermissionMapper;
import com.jc.ds.model.*;
import com.jc.service.permission.PermissionService;
import com.jc.service.user.UserService;
import com.jc.service.userrole.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jc.cds.model.CustomRole;
import com.jc.ds.base.service.BaseServiceImpl;
import com.jc.ds.mapper.BaseCustomMapper;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.text.html.ObjectView;
import java.util.*;

@Service
public class RoleServiceImpl extends BaseServiceImpl<Role, CustomRole, Long> implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override

    public BaseCustomMapper<CustomRole, Long> getCustomMapper() {
        return null;
    }


    /**
     * 查询所有的角色
     */
    @Override
    public Map<String, Object> queryRole(Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();

        List<Role> roles = this.roleMapper.selectAll(new Role() {{
            if (!CheckNullUtils.isNull(String.valueOf(param.get("id")))) {
                setId(Long.valueOf(String.valueOf(param.get("id"))));
            }
        }});
        ArrayList<Role> roles1 = new ArrayList<>();
        for (Role role : roles) {
            if (role.getPid() != 0) {
                roles1.add(role);
            }
        }
        result.put("data", roles1);
        result.put("msg", "查询成功");
        result.put("code", "10000");
        return result;
    }

    /**
     * 修改角色
     */
    @Override
    @Transactional
    public Map<String, Object> roleUpdate(Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();

        if (CheckNullUtils.isNull(String.valueOf(param.get("roleName")))) {
            result.put("data", "未接收到参数");
            result.put("msg", "失败");
            result.put("code", "6666");
            return result;
        }
        if (CheckNullUtils.isNull(String.valueOf(param.get("roleDescription")))) {
            result.put("data", "未接收到参数");
            result.put("msg", "失败");
            result.put("code", "6666");
            return result;
        }
        if (CheckNullUtils.isNull(String.valueOf(param.get("updateRoleId")))) {
            result.put("data", "未接收到参数");
            result.put("msg", "失败");
            result.put("code", "6666");
            return result;
        }

        int i = this.roleMapper.updateByPrimaryKeySelective(new Role() {{
            setId(Long.valueOf(String.valueOf(param.get("updateRoleId"))));
            setDescription(String.valueOf(param.get("roleDescription")));
            setName(String.valueOf(param.get("roleName")));
        }});

        if (i != 1) {
            result.put("data", "失败");
            result.put("msg", "失败!~");
            result.put("code", "6666");
            return result;
        }

        result.put("data", "成功");
        result.put("msg", "成功");
        result.put("code", "10000");
        return result;
    }

    /**
     * 新增角色
     */
    @Override
    @Transactional
    public Map<String, Object> addRole(Map<String, Object> param) {

        Map<String, Object> result = new HashMap<>();

        if (CheckNullUtils.isNull(String.valueOf(param.get("fatherRoleId")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到fatherRoleId");
            result.put("code", "6666");
            return result;
        }


        if (CheckNullUtils.isNull(String.valueOf(param.get("roleName")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到roleName");
            result.put("code", "6666");
            return result;
        }

        if (CheckNullUtils.isNull(String.valueOf(param.get("roleDescription")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到roleDescription");
            result.put("code", "6666");
            return result;
        }

        String fatherRoleIds = "";
        List<Role> fatherRole = new ArrayList<>();
        if (String.valueOf(param.get("fatherRoleId")).equals("0")) {
            fatherRoleIds = "0";
        } else {
            fatherRole = super.queryAll(new Role() {{
                setId(Long.valueOf(String.valueOf(param.get("fatherRoleId"))));
            }});
            fatherRoleIds = String.valueOf(fatherRole.get(0).getId());
        }

        if (fatherRole.size() > 1) {
            result.put("data", "失败");
            result.put("msg", "父级角色存在多个~");
            result.put("code", "6666");
            return result;
        }


        String finalFatherRoleIds = fatherRoleIds;
        int insert = this.roleMapper.insert(new Role() {{
            setDescription(String.valueOf(param.get("roleDescription")));
            setName(String.valueOf(param.get("roleName")));
            setPid(Long.valueOf(finalFatherRoleIds));
        }});
        if (insert != 1) {
            result.put("data", "fail");
            result.put("msg", "添加失败");
            result.put("code", "6666");
            return result;
        }

        result.put("data", "success");
        result.put("msg", "添加成功");
        result.put("code", "10000");
        return result;

    }

    /**
     * 删除角色
     */
    @Override
    @Transactional
    public Map<String, Object> delRole(Map<String, Object> param) {

        Map<String, Object> result = new HashMap<>();

        if (CheckNullUtils.isNull(String.valueOf(param.get("id")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到id");
            result.put("code", "6666");
            return result;
        }


        //父角色删除所有子
        List<Role> role = super.queryAll(new Role() {{
            setId(Long.valueOf(String.valueOf(param.get("id"))));
        }});

        if (role.get(0).getPid() == 0) {
            List<Role> roles = super.queryAll(new Role() {{
                setPid(role.get(0).getId());
            }});
            for (Role role1 : roles) {
                super.remove(role1.getId());
            }
        }

        this.roleMapper.deleteByPrimaryKey(Long.valueOf(String.valueOf(param.get("id"))));


        List<RolePermission> rolePermissions = this.rolePermissionMapper.selectAll(new RolePermission() {{
            setRoleId(Long.valueOf(String.valueOf(param.get("id"))));
        }});

        for (RolePermission rolePermission : rolePermissions) {
            this.rolePermissionMapper.deleteByPrimaryKey(rolePermission.getId());
        }

        List<UserRole> userRoles = this.userRoleService.queryAll(new UserRole() {{
            setRoleId(Long.valueOf(String.valueOf(param.get("id"))));
        }});
        if (userRoles.size() > 0) {

            this.userRoleService.remove(userRoles.get(0).getId());
        }


        result.put("data", "success");
        result.put("msg", "删除成功");
        result.put("code", "10000");
        return result;
    }

    /**
     * 给角色赋予对应的菜单编号
     */
    @Override
    @Transactional
    public Map<String, Object> giveRoleMenu(Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();
        if (CheckNullUtils.isNull(String.valueOf(param.get("param")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到param");
            result.put("code", "6666");
            return result;
        }
        Map<String, Object> param1 = JSONObject.parseObject(String.valueOf(param.get("param")));

        if (CheckNullUtils.isNull(String.valueOf(param1.get("ids")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到菜单id");
            result.put("code", "6666");
            return result;
        }
        if (CheckNullUtils.isNull(String.valueOf(param1.get("name")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到菜单名字");
            result.put("code", "6666");
            return result;
        }

        String name = String.valueOf(param1.get("name"));
        List<String> ids = (List<String>) JSONObject.parse(String.valueOf(param1.get("ids")));

        HashSet<String> idsSet = new HashSet<>();
        for (String id : ids) {
            idsSet.add(id);
        }


        List<Role> roles = this.roleMapper.selectAll(new Role() {{
            setName(name);
        }});
        Long roleId = roles.get(0).getId();


        List<RolePermission> rolePermissions = this.rolePermissionMapper.selectAll(new RolePermission() {{
            setRoleId(roleId);
        }});

        for (RolePermission rolePermission : rolePermissions) {
            List<Permission> permissions = this.permissionService.queryAll(new Permission() {{
                setId(rolePermission.getPermissionId());
                setPermissionType(1);
            }});
            if (permissions.size() > 0) {
                this.rolePermissionMapper.deleteByPrimaryKey(rolePermission.getId());
            }

        }


        int insert = 0;
        for (String id : idsSet) {
            List<RolePermission> rolePermissions1 = this.rolePermissionMapper.selectAll(new RolePermission() {{
                setRoleId(roleId);
                setPermissionId(Long.valueOf(id));
            }});
            for (RolePermission rolePermission : rolePermissions1) {
                this.rolePermissionMapper.deleteByPrimaryKey(rolePermission.getId());
            }

            insert = this.rolePermissionMapper.insert(new RolePermission() {{
                setRoleId(roleId);
                setPermissionId(Long.valueOf(id));
            }});
        }


        result.put("data", "success");
        result.put("msg", "赋予权限成功");
        result.put("code", "10000");
        return result;

    }

    /**
     * 根据roleId查询用户
     */
    @Override
    public Map<String, Object> queryUserByRoleId(Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();
        if (CheckNullUtils.isNull(String.valueOf(param.get("id")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到id值");
            result.put("code", "6666");
            return result;
        }
        List<UserRole> userRoles = this.userRoleService.queryAll(new UserRole() {{
            setRoleId(Long.valueOf(String.valueOf(param.get("id"))));
        }});
        ArrayList<Object> objects = new ArrayList<>();
        for (UserRole userRole : userRoles) {
            Long userId = userRole.getUserId();
            List<User> users = this.userService.queryAll(new User() {{
                setId(userId);
            }});
            objects.add(users.get(0));
        }

        result.put("data", objects);
        result.put("msg", "查询成功~");
        result.put("code", "10000");
        return result;
    }

    /**
     * 根据roleId userId删除关联
     */
    @Override
    @Transactional
    public Map<String, Object> delUserRole(Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();
        if (CheckNullUtils.isNull(String.valueOf(param.get("userId")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到userId");
            result.put("code", "6666");
            return result;
        }
        if (CheckNullUtils.isNull(String.valueOf(param.get("roleId")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到roleId");
            result.put("code", "6666");
            return result;
        }
        String roleId = String.valueOf(param.get("roleId"));
        String userId = String.valueOf(param.get("userId"));

        List<UserRole> userRoles = this.userRoleService.queryAll(new UserRole() {{
            setRoleId(Long.valueOf(roleId));
            setUserId(Long.valueOf(userId));
        }});
        int del = 0;
        for (UserRole userRole : userRoles) {
            del = this.userRoleService.remove(userRole.getId());
        }
        if (del != 1) {
            result.put("data", "fail");
            result.put("msg", "失败");
            result.put("code", "6666");
            return result;
        }

        result.put("data", "success");
        result.put("msg", "成功");
        result.put("code", "10000");
        return result;
    }

    /**
     * 根据roleId查询role
     */
    @Override
    public Map<String, Object> queryRoleByRoleId(Map<String, Object> param) {

        Map<String, Object> result = new HashMap<>();
        if (CheckNullUtils.isNull(String.valueOf(param.get("id")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到roleId");
            result.put("code", "6666");
            return result;
        }

        String roleId = String.valueOf(param.get("id"));

        List<Role> roles = super.queryAll(new Role() {{
            setId(Long.valueOf(roleId));
        }});

        result.put("data", roles);
        result.put("code", 10000);
        result.put("msg", "查询成功");
        return result;
    }

    /**
     * 根据roleId查询对应的菜单列表
     */
    @Override
    public Map<String, Object> queryMenuListsByRoleId(Map<String, Object> param) {


        Map<String, Object> result = new HashMap<>();
        if (CheckNullUtils.isNull(String.valueOf(param.get("id")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到roleIdToFindMenuL");
            result.put("code", "6666");
            return result;
        }

        List<RolePermission> rolePermissions = this.rolePermissionMapper.selectAll(new RolePermission() {{
            setRoleId(Long.valueOf(String.valueOf(param.get("id"))));
        }});

        ArrayList<Object> objects = new ArrayList<>();
        rolePermissions.forEach(rolePermission -> {
            List<Permission> permissions = this.permissionService.queryAll(new Permission() {{
                setId(rolePermission.getPermissionId());
                setPermissionType(1);
            }});
            if (permissions.size() != 0) {
                objects.add(permissions);
            }

        });
        result.put("data", objects);
        result.put("code", 10000);
        result.put("msg", "查询成功");
        return result;
    }

    /**
     * 查询所有的角色包含上下级
     */
    @Override
    public Map<String, Object> queryAllRoles() {

        List<Role> roles = super.queryAll(new Role() {{
            setPid(Long.valueOf("0"));
        }});

        Map<String, Object> result = new HashMap<>();
        ArrayList<Object> objects = new ArrayList<>();
        for (Role role : roles) {
            Map<String, Object> map = WebUtils.beanToMap(role);
            List<Role> roles1 = super.queryAll(new Role() {{
                setPid(role.getId());
            }});
            map.put("childRole", roles1);
            objects.add(map);
        }
        result.put("data", objects);
        result.put("code", 10000);
        result.put("msg", "查询成功");
        return result;
    }

    /**
     * 修改角色
     */
    @Override
    public Map<String, Object> modifyRoleName(Map<String, Object> param) {
        Map<String, Object> result = new HashMap<>();
        if (CheckNullUtils.isNull(String.valueOf(param.get("name")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到name");
            result.put("code", "6666");
            return result;
        }
        if (CheckNullUtils.isNull(String.valueOf(param.get("id")))) {
            result.put("data", "失败");
            result.put("msg", "没有接收到id");
            result.put("code", "6666");
            return result;
        }


        List<Role> name = super.queryAll(new Role() {{
            setId(Long.valueOf(String.valueOf(param.get("id"))));
        }});
        if (name.size() == 0) {
            result.put("data", "失败");
            result.put("msg", "没有查到找角儿色");
            result.put("code", "6666");
            return result;
        }

        super.modify(new Role() {{
            setId(Long.valueOf(String.valueOf(param.get("id"))));
            setName(String.valueOf(param.get("name")));

        }}, false);

        result.put("data", "success");
        result.put("msg", "success");
        result.put("code", "10000");
        return result;
    }
}
